<template>
    <j-modal :title="title" :width="800" :visible="visible" :confirmLoading="confirmLoading" :okButtonProps="{ props: {disabled: disableSubmit} }"
        @ok="handleOk" @cancel="handleCancel" cancelText="关闭" :okText="msgStatus==1?'确认审核':'确定'">
        <a-spin :spinning="confirmLoading">
            <a-form :form="form" :label-col="{ span: 3 }" :wrapper-col="{ span: 12 }">
                <a-form-item label="消息主题">
                    <a-input v-decorator="['msgTitle', { rules: [{ required: true, message: '请输入消息主题!' }] }]"
                        placeholder="请输入消息主题" :disabled="disableSubmit"/>
                </a-form-item>
                <a-form-item label="消息内容">
                    <a-textarea v-decorator="['msgContent', {}]" placeholder="请输入消息内容" :disabled="disableSubmit"/>
                </a-form-item>
                <a-form-item label="附件">
                    <a-upload v-if="!attachmentUrl[0]" :showUploadList="false" :action="url.fileUpload"
                        :data="{ 'isup': 1, 'dir': 'notice/attachments' }" :headers="headers" :multiple="false"
                        :beforeUpload="beforeUpload" @change="handleChange"
                        :disabled="disableSubmit">
                        <a-button type="primary" @click="check()"  :disabled="disableSubmit">上传</a-button>
                    </a-upload>
                    <span v-if="attachmentUrl[0]" style="margin-left: 18px;">
                        <a :href="attachmentUrl[0].url" target="_blank">{{ attachmentUrl[0].name
                            }}</a>
                        <a-button type="link" v-if="!disableSubmit" @click="deleteFile(0)">删除</a-button>
                    </span>
                </a-form-item>
                <a-form-item label="添加渠道" required>
                    <a-button v-if="!disableSubmit" type="primary" @click="handleShowChannel">添加</a-button>
                    <a-button v-if="!disableSubmit" type="danger" @click="deleteData" style="margin-left: 18px;"
                        :disabled="selectedRowKeys.length == 0">删除</a-button>
                </a-form-item>
                <a-table :row-selection="{ selectedRowKeys, onChange: onSelectChange }" :pagination="false"
                    :columns="columns" rowKey="storeId" :data-source="sourceData" size="small" :scroll="{ y: 300 }" />
                <a-button type="link">共{{ sourceData.length }}条</a-button>

            </a-form>
        </a-spin>
        <sys-msgNoticeChannel-modal v-if="!disableSubmit" ref="sysMsgNoticeChannelModalRef" @selectFinished="selectFinished"
            :sourceData="sourceData" />

    </j-modal>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import moment from "moment"
import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import sysMsgNoticeChannelModal from './SysMsgNoticeChannelModal.vue';


export default {
    name: "SysMsgNoticeModal",
    data() {
        return {
            title: "操作",
            visible: false,
            model: {},
            confirmLoading: false,
            disableSubmit:false,
            form: this.$form.createForm(this),
            url: {
                add: "/system/sysMsgNotice/add",
                edit: "/system/sysMsgNotice/edit",
                queryById: '/system/sysMsgNotice/queryById',
                fileUpload: window._CONFIG['domianURL'] + "/sys/common/ossUpload",
            },
            attachmentUrl: [],
            headers: {},
            selectedRowKeys: [],
            sourceData: [],
            columns: [
                {
                    title: '渠道编码',
                    align: 'center',
                    dataIndex: 'channelId',
                    width: 80
                },
                {
                    title: '渠道名称',
                    align: 'center',
                    dataIndex: 'channelName',
                    width: 100
                },
                {
                    title: '经销商编号',
                    align: 'center',
                    dataIndex: 'storeCode',
                    width: 150
                },
                {
                    title: '经销商名称',
                    align: 'center',
                    dataIndex: 'storeName'
                },
            ],
            msgStatus:0 // 状态
        }
    },
    computed: {

    },
    created() {
        const token = Vue.ls.get(ACCESS_TOKEN);
        this.headers = { "X-Access-Token": token };
    },
    methods: {
        // 先完善主题
        check(event) {
            console.log(this.form.getFieldValue('msgTitle'));
            if (!this.form.getFieldValue('msgTitle')) {
                this.$message.warning('请先补充消息主题!');
                event = event || window.event;
                if (event.stopPropagation) {
                    event.stopPropagation();
                } else {
                    event.cancelBubble = true;
                }
            }
        },
        beforeUpload(file) {
            console.log(file);
            const title = this.form.getFieldValue('msgTitle')
            // console.log(title);
            // if(!title){
            //     this.$message.warning('请先补充消息主题!');
            //     return false;
            // }
            return new Promise((resolve) => {
                //修改文件名
                const newFileName = title.trim() + '.' + file.name.split('.').pop();
                //创建一个新的文件对象，使用新的文件名
                const newFiles = new File([file], newFileName, {
                    type: file.type
                });
                newFiles.uid = file.uid;
                console.log(newFiles);
                resolve(newFiles);
            })
        },
        handleChange(info) {
            this.pictureUrl = "";
            if (info.file.status === 'uploading') {
                this.uploadLoading = true;
                return
            }
            if (info.file.status === 'done') {
                var response = info.file.response;
                this.uploadLoading = false;
                console.log(response);
                if (response.success) {
                    this.attachmentUrl.push({ name: response.result.fileName, url: response.result.url });
                } else {
                    this.$message.warning(response.message);
                }
            }
        },
        deleteFile(index) {
            this.attachmentUrl.splice(index, 1);
        },
        onSelectChange(selectedRowKeys) {
            console.log('selectedRowKeys changed: ', selectedRowKeys);
            this.selectedRowKeys = selectedRowKeys;
        },

        // 选择渠道
        handleShowChannel() {
            this.$refs.sysMsgNoticeChannelModalRef.open();
        },
        // 新增
        add() {
            this.edit({},0);
        },
        // status:0 编辑  1 审核
        edit(record,status) {
            this.visible = true;
            this.selectedRowKeys = [];
            this.sourceData = [];
            this.attachmentUrl = [];
            this.$nextTick(()=>{
                this.model = Object.assign({}, record);
                this.form.resetFields();
                !this.disableSubmit && this.$refs.sysMsgNoticeChannelModalRef.clear();
            })
            this.msgStatus = status;
           
            if(!record.id){return}
            // 获取明细数据
            getAction(this.url.queryById, { id: record.id }).then((res) => {
                if (res.success) {
                    const det = res.result;
                    this.model = det;

                    this.$nextTick(() => {
                        this.form.setFieldsValue(pick(this.model, 'partnerId', 'msgTitle', 'msgContent', 'msgStatus', 'attachmentName', 'attachmentUrl', 'auditBy', 'deleteStatus'))
                        if (record.attachmentUrl) {
                            this.attachmentUrl = [{
                                url: det.attachmentUrl,
                                name: det.attachmentName
                            }]
                        }
                        this.sourceData = det.noticeRecordList;
                        //时间格式化
                        // this.form.setFieldsValue({ auditTime: this.model.auditTime ? moment(this.model.auditTime) : null })
                    });
                }
            })
        },
        // 选择的数据
        selectFinished(selectRows) {
            if (!this.sourceData.length) {
                this.sourceData = selectRows
                return;
            }
            selectRows.forEach(x => {
                const index = this.sourceData.findIndex(item => item.storeId == x.storeId)
                if (index < 0) {
                    console.log(x);
                    this.sourceData.push(x)
                }
            })
        },
        // 删除数据
        deleteData() {
            if (!this.selectedRowKeys.length) {
                return
            }
            this.selectedRowKeys.forEach(x => {
                const index = this.sourceData.findIndex(y => y.storeId == x);
                index >= 0 && this.sourceData.splice(index, 1);
            })
            this.selectedRowKeys = []
        },
        close() {
            this.$emit('close');
            this.visible = false;
        },
        handleOk() {
            const that = this;
            if (!this.sourceData.length) {
                that.$message.warning('请选择渠道');
                return;
            }
            // 触发表单验证
            this.form.validateFields((err, values) => {
                if (!err) {
                    that.confirmLoading = true;
                    let httpurl = '', method = '';
                    if (!this.model.id) {
                        httpurl += this.url.add;
                        method = 'post';
                    } else {
                        httpurl += this.url.edit;
                        method = 'put';
                    }
                    let formData = {
                        ...this.model,
                        ...values,
                        attachmentUrl: this.attachmentUrl[0] && this.attachmentUrl[0].url,
                        attachmentName: this.attachmentUrl[0] && this.attachmentUrl[0].name,
                        noticeRecordList: this.sourceData.map(x => ({ storeId: x.storeId })),
                        msgStatus:this.msgStatus
                    }
                    //时间格式化
                    // formData.auditTime = formData.auditTime ? formData.auditTime.format('YYYY-MM-DD HH:mm:ss') : null;

                    console.log(formData)
                    httpAction(httpurl, formData, method).then((res) => {
                        if (res.success) {
                            that.$message.success(res.message);
                            that.$emit('ok');
                            this.visible = false;
                        } else {
                            that.$message.warning(res.message);
                        }
                    }).finally(() => {
                        that.confirmLoading = false;
                        that.close();
                    })



                }
            })
        },
        handleCancel() {
            this.close()
        },


    },
    components: {
        sysMsgNoticeChannelModal
    }
}
</script>

<style lang="less" scoped></style>